{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dd013b46-db5a-4f39-bd4b-a834c2d85d4f",
   "metadata": {},
   "source": [
    "# 快速排序"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20a57170-e129-4cdb-91ab-40900bcf88a2",
   "metadata": {},
   "source": [
    "快速排序采用分治策略，但不使用额外的存储空间。不过，代价是列表可能不会被一分为二。出现这种情况时，算法的效率会有所下降。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fad5c82a-2b7c-47d1-a766-3d692007d5d2",
   "metadata": {},
   "source": [
    "快速排序算法首先选出一个**基准值**。尽管有很多种选法，但为简单起见，选取列表中的第一个元素作为基准值。基准值的作用是帮助切分列表。在最终的有序列表中，基准值的位置通常被称作分割点，算法在分割点切分列表，以进行对快速排序的子调用。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9196956-8da5-4b63-890e-492f131c0d29",
   "metadata": {},
   "source": [
    "在下图中，元素 54 将作为第一个基准值。下一步是分区操作。它会找到分割点，同时将其他元素放到正确的一边——要么大于基准值，要么小于基准值。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d563d1a1-3415-4e12-b67f-2e5b9e148fc3",
   "metadata": {},
   "source": [
    "![快速排序1](quick_sort1.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75e113ee-1ced-415e-94d0-c9afb94a816a",
   "metadata": {},
   "source": [
    "分区操作首先找到两个坐标——leftmark 和 rightmark——它们分别位于列表剩余元素的开头和末尾，如下图所示。分区的目的是根据待排序元素与基准值的相对大小将它们放到正确的一边，同时逐渐逼近分割点。下图展示了为元素 54 寻找正确位置的过程。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b095dbe-2e63-4cd0-8bf7-edfe0fc13d6e",
   "metadata": {},
   "source": [
    "![快速排序2](quick_sort2.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f6ae157-bf6c-4c08-a11c-0279adc3c814",
   "metadata": {},
   "source": [
    "首先加大 leftmark，直到遇到一个大于基准值的元素。然后减小 rightmark，直到遇到一个小于基准值的元素。这样一来，就找到两个与最终的分割点错序的元素。本例中，这两个元\n",
    "素就是 93 和 20。互换这两个元素的位置，然后重复上述过程。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "785d2a6e-e5e8-46c5-85d7-1d8c02331bee",
   "metadata": {},
   "source": [
    "当 rightmark 小于 leftmark 时，过程终止。此时，rightmark 的位置就是分割点。将基准值与当前位于分割点的元素互换，即可使基准值位于正确位置，如下图所示。分割点左边的所有元素都小于基准值，右边的所有元素都大于基准值。因此，可以在分割点处将列表一分为二，并针对左右两部分递归调用快速排序函数。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11316130-b53d-4603-b343-e77e3e7116d8",
   "metadata": {},
   "source": [
    "![快速排序3](quick_sort3.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "096c144c-c4d8-44d7-a012-274aaa27a598",
   "metadata": {},
   "source": [
    "在下面代码中，快速排序函数 quick_sort 调用了递归函数 quick_sort_helper。quick_sort_helper 首先处理和归并排序相同的基本情况。如果列表的长度小于或等于 1，说明\n",
    "它已经是有序列表；如果长度大于 1，则进行分区操作并递归地排序。分区函数 partition 实现了前面描述的过程。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ff9ac844-9401-41c2-bb9b-5272429f838b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def quick_sort(alist):\n",
    "    quick_sort_helper(alist, 0, len(alist)-1)\n",
    "\n",
    "def quick_sort_helper(alist, first, last):\n",
    "    if first < last:\n",
    "        splitpoint = partition(alist, first, last)\n",
    "\n",
    "        quick_sort_helper(alist, first, splitpoint-1)\n",
    "        quick_sort_helper(alist, splitpoint+1, last)\n",
    "\n",
    "def partition(alist, first, last):\n",
    "    pivotvalue = alist[first]\n",
    "\n",
    "    leftmark = first + 1\n",
    "    rightmark = last\n",
    "\n",
    "    done = False\n",
    "    while not done:\n",
    "\n",
    "        while leftmark <= rightmark and alist[leftmark] <= pivotvalue:\n",
    "            leftmark = leftmark + 1\n",
    "\n",
    "        while alist[rightmark] >= pivotvalue and rightmark >= leftmark:\n",
    "            rightmark = rightmark - 1\n",
    "\n",
    "        if rightmark < leftmark:\n",
    "            done = True\n",
    "        else:\n",
    "            temp = alist[leftmark]\n",
    "            alist[leftmark] = alist[rightmark]\n",
    "            alist[rightmark] = temp\n",
    "\n",
    "    temp = alist[first]\n",
    "    alist[first] = alist[rightmark]\n",
    "    alist[rightmark] = temp\n",
    "\n",
    "    return rightmark"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "86a2f938-93d8-417d-8240-0da90648c33e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "before sorting: [54, 26, 93, 17, 77, 31, 44, 55, 20]\n",
      "after sorting: [17, 20, 26, 31, 44, 54, 55, 77, 93]\n"
     ]
    }
   ],
   "source": [
    "a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]\n",
    "print(f\"before sorting: {a_list}\")\n",
    "quick_sort(a_list)\n",
    "print(f\"after sorting: {a_list}\")\n",
    "assert a_list == sorted(a_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "dc8e403f-04a8-4c26-b6c3-0db7725229ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "from random import randint, seed\n",
    "seed(13)\n",
    "lst_to_sort = [randint(100, 999) for _ in range(1000)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2b2ffa03-89dc-4a76-99ef-d43e2c8e905d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9.62 ms ± 227 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit quick_sort(lst_to_sort)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17077678-c58c-4b61-89d8-62b8f2d2ccb3",
   "metadata": {},
   "source": [
    "在分析 quick_sort 函数时要注意，对于长度为 n 的列表，如果分区操作总是发生在列表的中部，就会切分 $logn$ 次。为了找到分割点，n 个元素都要与基准值比较。所以，时间复杂度是 $O(n logn)$ 。另外，快速排序算法不需要像归并排序算法那样使用额外的存储空间。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5278c06-743a-4bdf-bf26-3e122e336d24",
   "metadata": {},
   "source": [
    "不幸的是，最坏情况下，分割点不在列表的中部，而是偏向某一端，这会导致切分不均匀。在这种情况下，含有 n 个元素的列表可能被分成一个不含元素的列表与一个含有 n–1 个元素的列\n",
    "表。然后，含有 n–1 个元素的列表可能会被分成不含元素的列表与一个含有 n–2 个元素的列表，依此类推。这会导致时间复杂度变为 $O(n^2)$ ，因为还要加上递归的开销。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38b69575-bdff-4dd8-9784-6faa2b48977f",
   "metadata": {},
   "source": [
    "前面提过，有多种选择基准值的方法。可以尝试使用三数取中法避免切分不均匀，即在选择基准值时考虑列表的头元素、中间元素与尾元素。本例中，先选取元素 54、77 和 20，然后取\n",
    "中间值 54 作为基准值（当然，它也是之前选择的基准值）。这种方法的思路是，如果头元素的正确位置不在列表中部附近，那么三元素的中间值将更靠近中部。当原始列表的起始部分已经有\n",
    "序时，这一招尤其管用。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a4dce84-e216-48b3-81de-059c59ac9e42",
   "metadata": {},
   "source": [
    "下面代码增加median3函数，实现了三数取中法，可以通过性能测试看出性能的提升。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "cd4bb017-b7de-49c4-bc38-2d0828623324",
   "metadata": {},
   "outputs": [],
   "source": [
    "def quick_sort(alist):\n",
    "    quick_sort_helper(alist, 0, len(alist)-1)\n",
    "\n",
    "def quick_sort_helper(alist, first, last):\n",
    "    if first < last:\n",
    "        splitpoint = partition(alist, first, last)\n",
    "\n",
    "        quick_sort_helper(alist, first, splitpoint-1)\n",
    "        quick_sort_helper(alist, splitpoint+1, last)\n",
    "\n",
    "def partition(alist, first, last):\n",
    "    median3(alist, first, last)\n",
    "    pivotvalue = alist[first]\n",
    "\n",
    "    leftmark = first + 1\n",
    "    rightmark = last\n",
    "\n",
    "    done = False\n",
    "    while not done:\n",
    "\n",
    "        while leftmark <= rightmark and alist[leftmark] <= pivotvalue:\n",
    "            leftmark = leftmark + 1\n",
    "\n",
    "        while alist[rightmark] >= pivotvalue and rightmark >= leftmark:\n",
    "            rightmark = rightmark - 1\n",
    "\n",
    "        if rightmark < leftmark:\n",
    "            done = True\n",
    "        else:\n",
    "            temp = alist[leftmark]\n",
    "            alist[leftmark] = alist[rightmark]\n",
    "            alist[rightmark] = temp\n",
    "\n",
    "    temp = alist[first]\n",
    "    alist[first] = alist[rightmark]\n",
    "    alist[rightmark] = temp\n",
    "\n",
    "    return rightmark\n",
    "\n",
    "def median3(alist, first, last):\n",
    "    center = (first + last) // 2\n",
    "    medianIndex = first\n",
    "\n",
    "    if alist[first] < alist[last]:\n",
    "        if alist[center] < alist[first]:\n",
    "            medianIndex = first\n",
    "        elif alist[last] < alist[center]:\n",
    "            medianIndex = last\n",
    "        else:\n",
    "            medianIndex = center\n",
    "    else:\n",
    "        if alist[center] < alist[last]:\n",
    "            medianIndex = last\n",
    "        elif alist[first] < alist[center]:\n",
    "            medianIndex = first\n",
    "        else:\n",
    "            medianIndex = center\n",
    "\n",
    "    if medianIndex != first:\n",
    "        temp = alist[first]\n",
    "        alist[first] = alist[medianIndex]\n",
    "        alist[medianIndex] = temp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "62e55fcf-7c22-484e-ae87-003d1aca2139",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "before sorting: [54, 26, 93, 17, 77, 31, 44, 55, 20]\n",
      "after sorting: [17, 20, 26, 31, 44, 54, 55, 77, 93]\n"
     ]
    }
   ],
   "source": [
    "a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]\n",
    "print(f\"before sorting: {a_list}\")\n",
    "quick_sort(a_list)\n",
    "print(f\"after sorting: {a_list}\")\n",
    "assert a_list == sorted(a_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1276ef90-c30f-4424-8ac8-5e950239e4b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from random import randint, seed\n",
    "seed(13)\n",
    "lst_to_sort = [randint(100, 999) for _ in range(1000)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "fa807744-360a-44a0-aafb-48133ecd5cae",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "490 μs ± 14.3 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit quick_sort(lst_to_sort)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61b457e5-9559-4ce4-9066-8385b7a01cb1",
   "metadata": {},
   "source": [
    "### 参考文档\n",
    "《Python数据结构与算法分析（第2版）》：5.3.6 快速排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23247a17-7d02-491c-b61b-885a3f86ab13",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
